<!--
 * @Author: licongwei
 * @Date: 2022-03-11 17:58:39
 * @FileDescription: 自动轮播按钮
-->
<template>
  <div class="carousel-btn" @click="handleCheckedChange('')">
    <i :class="['icon', { checked: isChecked }]"></i>
    <p class="text">轮播</p>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
interface Istate {
  // eslint-disable-next-line no-undef
  timer: NodeJS.Timer | null
  timeIndex: number
  isChecked: boolean
  handleCheckedChange: (isChecked: any) => void
  setCarousel: (timeIndex: number) => void
}
export default defineComponent({
  name: 'carouselBtn',
  setup() {
    // 轮播
    const router = useRouter()
    const route = useRoute()
    const state: Istate = reactive({
      timer: null,
      timeIndex: 0,
      isChecked: false,
      handleCheckedChange: (isChecked) => {
        if ([undefined, null, ''].includes(isChecked)) {
          state.isChecked = !state.isChecked
        } else {
          state.isChecked = isChecked
        }
        if (state.isChecked) {
          state.setCarousel(0)
        } else {
          state.timer && clearInterval(state.timer)
        }
      },
      setCarousel: (timeIndex: number) => {
        state.timeIndex = timeIndex
        router.push(carouselSetting.list[state.timeIndex])
        state.timer = setInterval(() => {
          state.timeIndex++
          if (state.timeIndex == carouselSetting.list.length) {
            state.timeIndex = 0
          }
          router.push(carouselSetting.list[state.timeIndex])
        }, 20 * 1000)
        // }, 1000)
      }
    })
    onBeforeUnmount(() => {
      state.timer && clearInterval(state.timer)
    })

    state.handleCheckedChange(carouselSetting.isOpen)
    return {
      ...toRefs(state)
    }
  }
})
</script>
<style lang="less" scoped>
.carousel-btn {
  position: absolute;
  top: 59px;
  right: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  .icon {
    position: relative;
    width: 20px;
    height: 20px;
    background-color: #164b86;
    box-shadow: 0 0 5px 2px #2684f7 inset;
    margin-right: 5px;
    &.checked {
      background: url('../img/icon-checked.png') no-repeat center center;
    }
  }
  .text {
    font-size: 18px;
    color: #31aaff;
    font-family: 'AliHYAiHei';
  }
}
</style>
